package org.suyafei.service.impl;

import com.mysql.cj.log.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.suyafei.config.RabbitMQConfig;
import org.suyafei.controller.request.AccountLoginRequest;
import org.suyafei.controller.request.AccountRegisterRequest;
import org.suyafei.enums.AuthTypeEnum;
import org.suyafei.enums.BizCodeEnum;
import org.suyafei.enums.EventMessageTypeEnum;
import org.suyafei.enums.SendCodeEnum;
import org.suyafei.manager.AccountManager;
import org.suyafei.model.AccountDO;
import org.suyafei.model.EventMessage;
import org.suyafei.model.LoginUser;
import org.suyafei.service.AccountService;
import org.suyafei.service.NotifyService;
import org.suyafei.utils.CommonUtil;
import org.suyafei.utils.IDUtil;
import org.suyafei.utils.JWTUtil;
import org.suyafei.utils.JsonData;

import java.util.List;

/**
 * @author 宿某人
 * @Date: 2021/12/06/4:39 下午
 * @Description:
 */
@Slf4j
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private NotifyService notifyService;

    @Autowired
    private AccountManager accountManager;

    @Autowired
    private static final Long FREE_TRAFFIC_PRODUCT_ID = 1L;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RabbitMQConfig rabbitMQConfig;
    /**
     * 用户注册
     *
     * * 手机验证码验证
     * * 密码加密（TODO）
     * * 账号唯一性检查(TODO)
     * * 插入数据库
     * * 新注册用户福利发放(TODO)
     * @param accountRegisterRequest
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public JsonData  register(AccountRegisterRequest accountRegisterRequest) {
        boolean checkCode = false;
        //手机验证码验证

        if (StringUtils.isNotBlank(accountRegisterRequest.getCode())) {
            checkCode = notifyService.checkCode(SendCodeEnum.USER_REGISTER, accountRegisterRequest.getPhone(), accountRegisterRequest.getCode());
        }
        if (!checkCode) {
            return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
        }

        AccountDO accountDO = new AccountDO();
        BeanUtils.copyProperties(accountRegisterRequest, accountDO);

        accountDO.setAuth(AuthTypeEnum.DEFAULT.name());

        //生成唯一的账号
        accountDO.setAccountNo(IDUtil.geneSnoFlakeId());

        //设置密码 秘钥 盐
        accountDO.setSecret("$1$" + CommonUtil.getStringNumRandom(8));

        String cryptPwd = Md5Crypt.md5Crypt(accountRegisterRequest.getPwd().getBytes(), accountDO.getSecret());
        accountDO.setPwd(cryptPwd);

        int rows = accountManager.insert(accountDO);
        log.info("rows{},注册成功{}", rows, accountDO);

        //用户注册成功，发放福利
        userRegisterInitTask(accountDO);

        return JsonData.buildSuccess();
    }

    /**
     * 1、根据手机号去找
     * @param request
     * @return
     */
    @Override
    public JsonData login(AccountLoginRequest request) {
        List<AccountDO> accountDOList = accountManager.findByPhone(request.getPhone());
        if (accountDOList != null && accountDOList.size() == 1) {
            AccountDO accountDO = accountDOList.get(0);
            String md5Crypt = Md5Crypt.md5Crypt(request.getPwd().getBytes(), accountDO.getSecret());

            if (md5Crypt.equalsIgnoreCase(accountDO.getPwd())) {
                LoginUser loginUser = LoginUser.builder().build();
                BeanUtils.copyProperties(accountDO, loginUser);


                //生成token
                String token = JWTUtil.geneJsonWebToken(loginUser);
                return JsonData.buildSuccess(token);
            }else {
                return JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR);
            }

        }else {
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNREGISTER);
        }
    }

    /**
     * 用户初始化，发放福利:流量包
     * @param accountDO
     */
    private void userRegisterInitTask(AccountDO accountDO) {
        EventMessage message = EventMessage.builder()
                .accountNo(accountDO.getAccountNo())
                .eventMessageType(EventMessageTypeEnum.TRAFFIC_FREE_INIT.name())
                .messageId(IDUtil.geneSnoFlakeId().toString())
                .bizId(FREE_TRAFFIC_PRODUCT_ID.toString())
                .build();
        rabbitTemplate.convertAndSend(rabbitMQConfig.getTrafficEventExchange(),
                rabbitMQConfig.getTrafficFreeInitRoutingKey(),message);

    }
}
